<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span v-color>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button v-if="checkPermission('importuser')" size="small" type="primary" @click="$router.push('/import?type=employees')">excel导入</el-button>
          <el-button v-if="checkPermission('exportuser')" size="small" type="warning" @click="handleDownload">excel导出</el-button>
          <el-button v-if="checkPermission('adduser')" size="small" type="danger" @click="addDialogVisible = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 30px">
        <el-table v-loading="loading" :data="list" border stripe>
          <el-table-column label="序号" type="index" :index="indexMethod" width="120" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template #default="{row}">
              <img
                v-imgerror
                :src="row.staffPhoto || 'https://img1.baidu.com/it/u=1864952117,272543708&fm=253&fmt=auto&app=138&f=JPEG?w=384&h=384' "
                width="120"
                height="120"
                style="border-radius: 50%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <!--  <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式岗位' : '临时岗位' }}
            </template>
          </el-table-column> -->
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column label="入职时间">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <!-- {{ row }} -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          style="margin-top: 30px"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <!-- 新增员工 -->
    <add-employee :add-dialog-visible.sync="addDialogVisible" @reload="getEmployees" />
    <!-- 二维码对话框 -->
    <el-dialog
      title="二维码"
      :visible="CodedialogVisible"
      width="16%"
      @close="CodedialogVisible = false"
    >
      <canvas ref="codeRef" />
    </el-dialog>
    <!-- 分配角色-->
    <assign-role :user-id="userId" :role-dialog-visible.sync="roleDialogVisible" />
  </div>
</template>

<script>
import qrCode from 'qrcode'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeMenu from '@/constant/employees'
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
import mix from '@/mixins'
// console.log(EmployeeMenu.hireType)
export default {
  name: 'Employees',
  components: { addEmployee, AssignRole },
  mixins: [mix],
  data() {
    return {
      list: [], // 员工列表
      total: 0, // 员工数量
      page: 1, // 页码
      size: 5, // 每页条数
      loading: false,
      addDialogVisible: false, // 新增员工对话框的布尔值
      CodedialogVisible: false, // 展示头像二维化对话框的布尔值
      roleDialogVisible: false, // 分配角色对话框的布尔值
      userId: '' // 点击分配角色的员工id
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {

    // 获取员工列表
    async getEmployees() {
      this.loading = true
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      this.list = rows
      this.total = total
      this.loading = false
    },
    // 每页条数发生变化
    handleSizeChange(val) {
      this.size = val
      this.getEmployees()
    },
    // 页码发生变化
    handleCurrentChange(val) {
      this.page = val
      this.getEmployees()
    },
    // 自定义索引列
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    delEmployee(id) {
      // 1. 确认消息提示
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 2. 发生请求
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        // 3. 重新渲染
        this.getEmployees()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 格式化聘用形式列
    formatter(row, column, cellValue, index) {
      // row 当前行信息 column是当前列的信息 cellValue 单元格的值  index是索引
      // console.log(row, column, cellValue, index)
      // return cellValue === 1 ? '正式的' : '临时的'
      const obj = EmployeeMenu.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    // 导出员工
    async handleDownload() {
      this.downloadLoading = true
      // 中英对照关系
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 1. 获取到所有员工
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      // console.log(rows)
      // 2. 将rows要处理成二维数组
      const data = this.get2Array(rows, headersRelations)
      // console.log(result)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          // 多表头
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          // 导出的表格标题
          header: Object.keys(headersRelations),
          // 合并配置
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          // 导出的表格的内容 data要求是一个二维数组
          data,
          // 导出的excel表格的文件名
          filename: '员工信息表',
          // 自适应宽度
          autoWidth: true,
          // 扩展名
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 处理二维数组的方法
    // forEach some every filter map find findexIndex reduce
    // push shift unshift pop slice join concat includes ....
    // MDN
    get2Array(rows, headersRelations) {
      return rows.map(item => {
        // console.log(item) // 员工
        // 定义导出的表格的标题数据并处理表格的内容为二维数组
        return Object.keys(headersRelations).map(str => {
          // console.log(str) // 表格标题每一个字符
          // console.log(headersRelations[str]) // 英文的键
          const englishKey = headersRelations[str]
          // console.log(item[englishKey]) // 筛出来的员工的信息字段
          // 处理聘用形式
          if (englishKey === 'formOfEmployment') {
            // console.log(item[englishKey])
            const o = EmployeeMenu.hireType.find(obj => obj.id === +item[englishKey])
            return o ? o.value : '未知'
            // 处理日期
          } else if (['correctionTime', 'timeOfEntry'].includes(englishKey)) {
            return formatDate(item[englishKey])
          } else {
            return item[englishKey]
          }
        })
      })
    },
    // 展示二维码
    showCode(info) {
      if (!info) return this.$message.info('默认头像不做展示')
      // 1. 展示对话框
      this.CodedialogVisible = true
      // 等到dom更新完毕后  vuedom更新是异步的
      this.$nextTick(() => {
        // 2. 生成二维码
      // qrCode.toCanvas('canvas标签', 信息)
        qrCode.toCanvas(this.$refs.codeRef, info)
      })
    },
    // 展示分配角色对话框
    showRoleDialog(id) {
      this.roleDialogVisible = true
      this.userId = id
    }
    // 导出员工-测试
    /* handleDownload() {
      this.downloadLoading = true
      console.log(import('@/vendor/Export2Excel'))
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          // 导出的表格标题
          header: ['姓名', '年龄', '性别', '住址'],
          // 导出的表格的内容 data要求是一个二维数组
          data: [
            ['翠花', 18, '男', '普陀'],
            ['李四', 28, '男', '上海'],
            ['王五', 38, '女', '北京']
          ],
          // 导出的excel表格的文件名
          filename: '信息表',
          // 自适应宽度
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    } */
  }
}
</script>

<style>

</style>
